package com.wfu.module_base.base;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.SparseArray;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

public abstract class BaseActivity extends RxAppCompatActivity {

    private SparseArray<View> views;
    protected static FragmentManager fm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        views = new SparseArray<>();
        fm = getSupportFragmentManager();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initResource();
        initWidget();
    }

    public abstract void initResource();

    public abstract void initWidget();

    public <T extends View> T getView(@IdRes int viewId) {
        View view = views.get(viewId);
        if (view == null) {
            view = findViewById(viewId);
            views.put(viewId, view);
        }
        return (T) view;
    }

    public <T extends Fragment> T findFragmentByTag(String tag) {
        return (T) fm.findFragmentByTag(tag);
    }

    public <T extends Fragment> T findFragmentById(@IdRes int fid) {
        return (T) fm.findFragmentById(fid);
    }

    /**
     * 跳转到指定的activity
     *
     * @param path 指定的Atc 的path
     */
    protected void redirect2Activity(String path) {
        ARouter.getInstance()
                .build(path)
                .navigation();
    }

    /**
     * 跳转到指定的activity并销毁当前Act
     *
     * @param path 指定的Atc 的path
     */
    protected void redirect2ActivityAndFinish(String path) {
        ARouter.getInstance()
                .build(path)
                .navigation();
        finish();
    }
}
